//
//  fabuViewController.m
//  YeDian
//
//  Created by 罗西 on 3/26/16.
//  Copyright © 2016 罗西. All rights reserved.
//

#import "fabuViewController.h"
#import "Tools.h"
#import "ConfigData.h"
#import "ASIFormDataRequest.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "JSON.h"
#import "LoginViewController.h"
#import "fabuTableViewCell.h"
#import "qiuzhixiangqingViewController.h"

@interface fabuViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSDictionary *myInfoDic;
}

@property (nonatomic,strong) UITableView *mainTableView;
@property (nonatomic,strong) NSArray *itemsArray;

@end


@implementation fabuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    CGRect frame_img= CGRectMake(0,(44-19)/2,19,19);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back2016"];
    CGRect frameBtn= CGRectMake(0, 0,50, 44);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    [homeBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    [homeBtn addSubview:backView];
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
    self.title = @"发布";
    
    [self loadUI];
}

-(void)backFn{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)loadUI{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    [self.view addSubview:self.mainTableView];
    [self.mainTableView setDataSource:self];
    [self.mainTableView setDelegate:self];
    [self.mainTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.mainTableView setBackgroundColor:[UIColor colorWithRed:252/255.0 green:252/255.0 blue:252/255.0 alpha:1.0]];
    //self
    
//        _itemsArray = @[[NSURL URLWithString:@"http://p5.sinaimg.cn/1172485740/180/25351348712143"],[NSURL URLWithString:@"https://www.baidu.com/s?tn=baidu&wd=cocoa&cq=62c4229601b691ac218c4affe2d087c4&rsv_dl=0_right_recom_21106&srcid=20986&rt=%E7%9B%B8%E5%85%B3%E6%9C%AF%E8%AF%AD&euri=06f2980b087a49708af58176ce87a317"],[NSURL URLWithString:@"http://p5.sinaimg.cn/1172485740/180/25351348712143"],[NSURL URLWithString:@"http://p5.sinaimg.cn/1172485740/180/25351348712143"],[NSURL URLWithString:@"http://p5.sinaimg.cn/1172485740/180/25351348712143"]];

    [self loadData];
}

-(void)loadData{
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString* mp_ = [accountDefaults objectForKey:@"uid"];
    //NSString* mp_=[ud objectForKey:@"mp"];
    if (!mp_) {
        return;
    }
    NSLog(@"mp:%@",mp_);
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"/index.php/appI/userPostList?uid="];
    loginURL=[loginURL stringByAppendingFormat:@"%@",mp_];
    NSLog(@"保存URL.loginURL==%@",loginURL);
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    
    [req startSynchronous];
    NSError *error = [req error];
    
    
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        myInfoDic=[response JSONValue];
        //NSString* uid=[myInfoDic objectForKey:@"uid"];
        //NSLog(@"ID%@",uid);
        
        _itemsArray = [response JSONValue];
        [self.mainTableView reloadData];
        //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
    }else{
        NSLog(@"move failed:%@", [error localizedDescription]);
    }
}

#pragma mark UITableViewDelegate/UITableViewDataSource

/**
 *  每个cell有多少行
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}


/**
 *  有多少个section
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _itemsArray.count;
}

/**
 *  section的title
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return nil;
}

/**
 *  header的距离
 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

/**
 *  row的高度
 */
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    float imgW = (SCREEN_WIDTH-40*2-10*2)/3;
    NSDictionary *dic = [_itemsArray objectAtIndex:indexPath.section];
    NSString *str1 = [NSString stringWithFormat:@"%@",[dic objectForKey:@"pic3"]];
    NSString *str2 = [NSString stringWithFormat:@"%@",[dic objectForKey:@"pic0"]];
    NSLog(@"lpic0 %lu",(unsigned long)str2.length);
    NSLog(@"lpic3 %lu",(unsigned long)str1.length);
    if (str2.length == 0) {
        return 30;
    }
    if (str1.length != 6 && ![[dic objectForKey:@"pic3"] isEqual:[NSNull null]]) {
        return 30+imgW*2+20;
    }
    if (str2.length != 0 && ![[dic objectForKey:@"pic0"] isEqual:[NSNull null]]) {
        return 30+imgW+20;
    }
    return 30;
}

/**
 *  cell的属性
 */
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    fabuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
        cell = [[fabuTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    NSDictionary *dic = [_itemsArray objectAtIndex:indexPath.section];
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *strr = [dic objectForKey:@"addTime"];
    if ([strr isEqual:[NSNull null]]) {
        strr = @"";
    }

    NSDate* dateBegin = [inputFormatter dateFromString:strr];
    [inputFormatter setDateFormat:@"MM-dd"];
    cell.dateLabel.text = [inputFormatter stringFromDate:dateBegin];
    NSString *st = [dic objectForKey:@"desc"];;
    if ([st isEqual:[NSNull null]]) {
        st = @"";
    }
    cell.titleLabel.text = st;
    
    NSMutableArray *array = [NSMutableArray new];
    NSString *pic0 = [dic objectForKey:@"pic0"];
    NSString *pic1 = [dic objectForKey:@"pic1"];
    NSString *pic2 = [dic objectForKey:@"pic2"];
    NSString *pic3 = [dic objectForKey:@"pic3"];
    NSString *pic4 = [dic objectForKey:@"pic4"];
    if (pic0.length!=0) {
        if ([pic0 rangeOfString:@"upload"].location == NSNotFound) {
            NSString *str = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic0"]];
            [array addObject:[NSURL URLWithString:str]];
        }else{
            NSString *str = [NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"pic0"]];
            [array addObject:[NSURL URLWithString:str]];
        }
        
    }
    if (pic1.length!=0) {
        if ([pic1 rangeOfString:@"upload"].location == NSNotFound) {
            NSString *str = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic1"]];
            [array addObject:[NSURL URLWithString:str]];
        }else{
            NSString *str = [NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"pic1"]];
            [array addObject:[NSURL URLWithString:str]];
        }
    }
    if (pic2.length!=0) {
        if ([pic2 rangeOfString:@"upload"].location == NSNotFound) {
            NSString *str = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic2"]];
            [array addObject:[NSURL URLWithString:str]];
        }else{
            NSString *str = [NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"pic2"]];
            [array addObject:[NSURL URLWithString:str]];
        }
    }
    if (pic3.length!=0) {
        if ([pic3 rangeOfString:@"upload"].location == NSNotFound) {
            NSString *str = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic3"]];
            [array addObject:[NSURL URLWithString:str]];
        }else{
            NSString *str = [NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"pic3"]];
            [array addObject:[NSURL URLWithString:str]];
        }
    }
    if (pic4.length!=0) {
        if ([pic4 rangeOfString:@"upload"].location == NSNotFound) {
            NSString *str = [NSString stringWithFormat:@"%@/upload/%@",HOST,[dic objectForKey:@"pic4"]];
            [array addObject:[NSURL URLWithString:str]];
        }else{
            NSString *str = [NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"pic4"]];
            [array addObject:[NSURL URLWithString:str]];
        }
    }
    
    [cell setImageView:array];
    return cell;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        NSDictionary * dic = _itemsArray[indexPath.section];
        NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
        NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
        NSString* mp_ = [accountDefaults objectForKey:@"uid"];
        //NSString* mp_=[ud objectForKey:@"mp"];
        if (!mp_) {
            return;
        }
        NSLog(@"mp:%@",mp_);
        NSString* loginURL=HOST;
        loginURL=[loginURL stringByAppendingString:@"/index.php/appI/delJob?jobId="];
        loginURL=[loginURL stringByAppendingFormat:@"%@",[dic objectForKey:@"id"]];
        NSLog(@"保存URL.loginURL==%@",loginURL);
        NSURL* url=[[NSURL alloc] initWithString:loginURL];
        ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
        
        
        [req startSynchronous];
        NSError *error = [req error];
        
        
        if (!error) {
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [MBProgressHUD hideHUDForView:app.window animated:YES];
            
            NSString *response = [req responseString];
            NSLog(@"保存返回结果%@",response);
            myInfoDic=[response JSONValue];
            //NSString* uid=[myInfoDic objectForKey:@"uid"];
            //NSLog(@"ID%@",uid);
            
            [self.view makeToast:@"删除成功" duration:2.0 position:@"center"];
            [self loadData];
            //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
        }else{
            NSLog(@"move failed:%@", [error localizedDescription]);
        }
        
    }];
    
    
    
    //    moreRowAction.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    deleteRowAction.backgroundColor = [UIColor redColor];

    
    
    // 将设置好的按钮放到数组中返回
    
    return @[ deleteRowAction];
    
    //    return @[deleteRowAction,moreRowAction];
}

/**
 *  点击事件
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic=[_itemsArray objectAtIndex:indexPath.section];
    NSString* merchant_id=[dic objectForKey:@"id"];
    qiuzhixiangqingViewController* ui=[[qiuzhixiangqingViewController alloc] init];
    ui.merchantId=merchant_id;
    [self.navigationController pushViewController:ui animated:NO];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
